<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/07/30
 * Time: 13:52
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller;

use app\common\model\JobApprove;
use app\common\model\JobFlowModule;
use app\common\service\system\ApprovalService;
use think\Controller;

abstract class BaseController extends Controller
{
    /**
     * 当前登录用户
     * @var \app\common\model\Admin $user
     */
    protected $user;

    /**
     * 当前登录仓库
     * @var \app\common\model\Warehouse $warehouse
     */
    protected $warehouse;

    protected function initialize()
    {
        parent::initialize();
        $this->user = session('lmterp');
        $this->warehouse = session('warehouse');
        $this->assign('check_status_pass', JobApprove::JOB_STATUS_PASS);
        $this->assign('check_status_reject', JobApprove::JOB_STATUS_REJECT);
        $this->assign('check_no_need', JobFlowModule::CHECK_NO_NEED);
        $this->assign('check_succ', JobFlowModule::CHECK_SUCC);
        $this->assign('curr_warehouse', $this->warehouse);
        $this->assign('domain_url', $this->request->domain());
        $this->assign('user', $this->user);
        $this->loadCommon();
    }

    /**
     * 预赋值
     * @date 2021/01/11
     * @author longli
     */
    protected function loadCommon()
    {}

    /**
     * 获取分页大小
     * @param array $search
     * @return int|null
     * @date 2020/09/15
     * @author longli
     */
    protected function getPageSize($search = [])
    {
        $perhaps = ['limit', 'page_size', 'pageSize'];
        if(empty($search)) $search = $this->request->request();
        foreach($perhaps as $v)
        {
            if(!empty($search[$v])) return $search[$v];
        }
        return null;
    }

    /**
     * 解析时间范围到 where 条件中
     * @param string $field 字段
     * @param int $date 时间，指定天数，默认为今天
     * @return array
     * @date 2020/09/16
     * @author longli
     */
    protected function parseScopeDateToWhere($field, $date = 0)
    {
        $where = [];
        $pdate = date('Y-m-d', strtotime("{$date}day"));
        if($date == 0)
        {
            $where[] = [$field, '>=', $pdate];
        }
        else if($date == -1)
        {
            $where[] = [$field, '>=', $pdate];
            $where[] = [$field, '<', date('Y-m-d')];
        }
        else
        {
            $where[] = [$field, "<=", $pdate];
        }
        return $where;
    }

    /**
     * 解析 layui date 时间范围
     * @param string $field 字段
     * @param string $date layui 时间格式
     * @return array
     * @date 2020/09/17
     * @author longli
     */
    protected function parseLayuiRangeDate($field = '', $date = '')
    {
        if(empty($field) && empty($date)) return [];
        $st = explode(' ~ ', $date);
        if(empty($field)) return $st;
        $endDay = date('Y-m-d', strtotime($st[1] . '+1day'));
        return [
            [$field, ">=", $st[0]],
            [$field, "<", $endDay]
        ];
    }

    /**
     * 渲染多类型关联模板
     * @param string $classes 模型类名
     * @param string|int $sn id 或者业务单号
     * @param string $template 模板路径
     * @param array $var 模板变量
     * @return string|void
     * @date 2021/01/12
     * @author longli
     */
    protected function renderTerp($classes, $sn, $template, $var = [])
    {
        if(!class_exists($classes) || !method_exists($classes, 'getBySn') || !view()->exists($template)) return;
        $model = $classes::getBySn($sn);
        if(empty($model)) return;
        $var = [
                "model" => $model,
            ] + $var;
        return view($template, $var)->getContent();
    }

    /**
     * 审批模块名称
     * @var string
     */
    protected $moduleName;

    /**
     * 审批工作流
     * @date 2021/01/16
     * @author longli
     */
    public function check()
    {
        if(empty($this->moduleName)) $this->error("未设置模块名称");
        $targetId = $this->request->request("target_id");
        $status = $this->request->request("status");
        $remark = $this->request->request("remark", '', 'trim');
        if(empty($targetId) || empty($status)) $this->error("非法请求");
        if(is_string($targetId)) $targetId = explode(',', $targetId);
        $jobFlow = ApprovalService::getInstance();
        $module = $jobFlow->getModule($this->moduleName);
        foreach($targetId as $pid)
        {
            if(!$jobFlow->approve($module->flow_id, $pid, $status, $remark))
            {
                $this->error(join(", ", $jobFlow->getError()));
            }
        }
        $this->success("审批通过");
    }

    /**
     * 模板赋值审批流
     * @param int $targetId 目标 id
     * @date 2021/02/15
     * @author longli
     */
    protected function assignCheck($targetId)
    {
        $module = ApprovalService::getInstance()->getModule($this->moduleName);
        $this->assign("jobFlowSettings", ApprovalService::getInstance()->getSettings($module->flow_id));
        $this->assign("jobFlows", ApprovalService::getInstance()->getJobFlows($module->flow_id, $targetId));
        $this->assign("jobFlowLast", ApprovalService::getInstance()->getLastJobFlow($module->flow_id, $targetId));
    }

    /**
     * 模板赋值附件
     * @param \app\common\model\BaseModel $model
     * @date 2021/03/06
     * @author longli
     */
    protected function assignAttachment(\app\common\model\BaseModel $model)
    {
        $pk = $model->getPk();
        $attachment = \app\common\model\SysAttachment::where([
            'id_type' => $model->getTable(),
            'ref_id' => $model->$pk
        ])->order('type, attach_id desc')->select();
        $temp = [];
        foreach($attachment as $a)
        {
            $temp[$a->type][] = $a;
        }
        $this->assign('attachment', $temp);
    }

    /**
     * 搜索
     * @param \app\common\model\BaseModel $model 搜索模型
     * @param array $condition 搜索条件
     * @date 2021/02/16
     * @author longli
     */
    protected function searchModel($model, $condition = [])
    {
        foreach($condition as $c => $cond)
        {
            $c = strtolower(trim($c));
            foreach($cond as $k => $f)
            {
                if(is_numeric($k)) $k = $f;
                $text = $this->request->request($k, '', 'trim');
                if(empty($text) && !is_numeric($text)) continue;
                if($c == 'eq')
                {
                    // 等于
                    $model->where($f, $text);
                }
                else if($c == 'gt')
                {
                    $model->where($f, "gt", $text);
                }
                else if($c == 'in')
                {
                    // IN
                    $model->whereIn($f, $text);
                }
                else if($c == 'like')
                {
                    // 模糊匹配
                    $model->where($f, "like", "%$text%");
                }
                else if($c == 'times')
                {
                    // 时间范围
                    $model->where($this->parseLayuiRangeDate($f, $text));
                }
                else if($c == 'range')
                {
                    // 范围
                    $model->where([
                        [$f, '>=', $text],
                        [$f, '<=', $text]
                    ]);
                }
            }
        }
    }
}